package model

import (
	"OJCenter/global"
	"OJCenter/idl"
	"github.com/mitchellh/mapstructure"
)

func (m *Model) CreateProblem(Problem *idl.Problem) error {
	err := m.P.InsertProblemInfo(Problem)
	if err != nil {
		return err
	}
	return nil
}

func (m *Model) DeleteProblemsFromContent(cid int64, pids []int64) (int, *[]int64) {
	sum := len(pids)
	var fu []int64
	for _, pid := range pids {
		err := m.Cd.DeleteContestDetailInfo(&idl.ContestDetailInfo{Pid: pid, Cid: cid})
		if err != nil {
			sum--
			fu = append(fu, cid)
			global.Logger.Errorf("uid:%v,delete Problem info failed,err:%v", pid, err)
		}
	}
	return sum, &fu
}

func (m *Model) DeleteProblems(pids []int64) (int, *[]int64) {
	sum := len(pids)
	var fu []int64
	for _, pid := range pids {
		err := m.P.DeleteProblemInfo(&idl.Problem{Pid: pid})
		if err != nil {
			sum--
			fu = append(fu, pid)
			global.Logger.Errorf("uid:%v,delete Problem info failed,err:%v", pid, err)
		}
	}
	return sum, &fu
}

func (m *Model) UpdateProblems(Problems *[]idl.Problem) (int, *[]idl.Problem) {
	sum := len(*Problems)
	var fu []idl.Problem
	for _, Problem := range *Problems {
		var info map[string]interface{}
		err := mapstructure.Decode(&Problem, &info)
		if err != nil {
			fu = append(fu, Problem)
			global.Logger.Error("update marshal failed")
			sum--
			continue
		}
		err = m.P.UpdateProblemInfo(info)
		if err != nil {
			sum--
			fu = append(fu, Problem)
			global.Logger.Errorf("uid:%v,update Problem info failed,err:%v", Problem.Pid, err)
		}
	}
	return sum, &fu
}

func (m *Model) GetProblemList(page, limit int) (*[]idl.Problem, error) {
	return m.P.GetProblemList(page, limit)
}

func (m *Model) SelectProblem(pro idl.Problem) (*[]idl.Problem, error) {
	return m.P.SelectProblems(&pro)
}
